package com.education.ai.service.impl;

import com.education.ai.dao.ExerciseDao;
import com.education.ai.entity.Exercise;
import com.education.ai.model.ExerciseRequest;
import com.education.ai.service.ExerciseService;
import com.education.ai.service.AiService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 练习题服务实现类
 */
@Service
@Slf4j
public class ExerciseServiceImpl implements ExerciseService {

    @Autowired
    private ExerciseDao exerciseDao;
    
    @Autowired
    @Qualifier("qwenWebClient")
    private WebClient qwenWebClient;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private AiService aiService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Value("${qwen.model:qwen-max}")
    private String model;

    @Override
    public List<Exercise> getAllExercises() {
        return exerciseDao.findAll();
    }

    @Override
    public Exercise getExerciseById(Long id) {
        return exerciseDao.findById(id).orElse(null);
    }

    @Override
    public List<Exercise> getExercisesBySubject(String subject) {
        return exerciseDao.findBySubject(subject);
    }

    @Override
    public List<Exercise> getExercisesByGrade(String grade) {
        return exerciseDao.findByGrade(grade);
    }

    @Override
    public List<Exercise> getExercisesBySubjectAndGrade(String subject, String grade) {
        return exerciseDao.findBySubjectAndGrade(subject, grade);
    }

    @Override
    public List<Exercise> getExercisesBySubjectAndGradeAndTopic(String subject, String grade, String topic) {
        return exerciseDao.findBySubjectAndGradeAndTopic(subject, grade, topic);
    }

    @Override
    public Exercise saveExercise(Exercise exercise) {
        return exerciseDao.save(exercise);
    }

    @Override
    public void deleteExercise(Long id) {
        exerciseDao.deleteById(id);
    }

    @Override
    public List<Exercise> generateExercises(String subject, String grade, String topic, int count) {
        return generateExercises(subject, grade, topic, count, null);
    }

    @Override
    public List<Exercise> generateExercises(String subject, String grade, String topic, int count, String teacherId) {
        ExerciseRequest request = new ExerciseRequest();
        request.setSubject(subject);
        request.setGrade(grade);
        request.setTopic(topic);
        request.setCount(count);
        request.setTeacherId(teacherId);
        return generateExercises(request);
    }

    @Override
    public List<Exercise> generateExercises(ExerciseRequest request) {
        // 构建提示词
        String prompt = buildPrompt(request);
        
        // 调用AI服务生成题目
        String response = aiService.generateContent(prompt);
        
        // 解析AI响应
        List<Exercise> exercises = parseAIResponse(response);
        
        // 设置教师ID
        exercises.forEach(exercise -> {
            exercise.setTeacherId(request.getTeacherId());
            exercise.setSubject(request.getSubject());
            exercise.setGrade(request.getGrade());
            exercise.setTopic(request.getTopic());
            exercise.setQuestionType(request.getQuestionType());
            exercise.setDifficulty(request.getDifficulty());
        });
        
        // 保存到数据库
        return exerciseDao.saveAll(exercises);
    }

    private String buildPrompt(ExerciseRequest request) {
        return String.format(
            "请生成以下要求的练习题：\n" +
            "学科：%s\n" +
            "年级：%s\n" +
            "主题：%s\n" +
            "题目类型：%s\n" +
            "难度：%s\n" +
            "题目数量：%d\n" +
            "请按照以下格式返回：\n" +
            "题目1：\n" +
            "内容：\n" +
            "答案：\n" +
            "解析：\n" +
            "难度：\n" +
            "---\n",
            request.getSubject(),
            request.getGrade(),
            request.getTopic(),
            request.getQuestionType(),
            request.getDifficulty(),
            request.getCount()
        );
    }

    private List<Exercise> parseAIResponse(String response) {
        List<Exercise> exercises = new ArrayList<>();
        String[] exerciseBlocks = response.split("---");
        
        for (String block : exerciseBlocks) {
            if (block.trim().isEmpty()) continue;
            
            Exercise exercise = Exercise.builder()
                .content(extractField(block, "内容："))
                .answer(extractField(block, "答案："))
                .analysis(extractField(block, "解析："))
                .difficulty(extractField(block, "难度："))
                .createdTime(LocalDateTime.now())
                .build();
            
            exercises.add(exercise);
        }
        
        return exercises;
    }

    private String extractField(String block, String fieldName) {
        int startIndex = block.indexOf(fieldName);
        if (startIndex == -1) return "";
        
        startIndex += fieldName.length();
        int endIndex = block.indexOf("\n", startIndex);
        if (endIndex == -1) endIndex = block.length();
        
        return block.substring(startIndex, endIndex).trim();
    }

    @Override
    public List<Map<String, Object>> formatExercisesForFrontend(List<Exercise> exercises, List<String> questionTypes) {
        List<Map<String, Object>> formattedExercises = new ArrayList<>();
        
        // 筛选出前端需要的题型的习题
        List<Exercise> filteredExercises = exercises.stream()
            .filter(e -> {
                String type = convertQuestionType(e.getQuestionType());
                return questionTypes.contains(type);
            })
            .collect(Collectors.toList());
        
        for (Exercise exercise : filteredExercises) {
            Map<String, Object> formattedExercise = new HashMap<>();
            formattedExercise.put("type", convertQuestionType(exercise.getQuestionType()));
            formattedExercise.put("content", exercise.getContent());
            formattedExercise.put("answer", exercise.getAnswer());
            formattedExercise.put("explanation", exercise.getAnalysis());
            
            // 如果是选择题，解析选项
            if (exercise.getQuestionType().contains("选择题")) {
                Map<String, String> options = parseOptions(exercise.getContent());
                formattedExercise.put("options", options);
            }
            
            formattedExercises.add(formattedExercise);
        }
        
        return formattedExercises;
    }
    
    @Override
    public List<Exercise> saveExercisesFromFrontend(String subject, String stage, String chapter, String textbook, List<Map<String, Object>> questions) {
        // 调用带teacherId参数的方法，传入null或从上下文获取
        return saveExercisesFromFrontend(subject, stage, chapter, textbook, questions, com.education.ai.util.TeacherContext.getCurrentTeacherId());
    }
    
    @Override
    public List<Exercise> saveExercisesFromFrontend(String subject, String stage, String chapter, String textbook, List<Map<String, Object>> questions, String teacherId) {
        List<Exercise> savedExercises = new ArrayList<>();
        
        for (Map<String, Object> question : questions) {
            String type = (String) question.get("type");
            String content = (String) question.get("content");
            String answer = (String) question.get("answer");
            String explanation = (String) question.get("explanation");
            
            Exercise exercise = Exercise.builder()
                .subject(subject)
                .grade(stage)
                .topic(chapter)
                .questionType(convertFrontendType(type))
                .content(content)
                .answer(answer)
                .analysis(explanation)
                .difficulty("中等") // 默认设置为中等难度
                .teacherId(teacherId) // 设置教师ID
                .createdTime(LocalDateTime.now())
                .build();
                
            // 如果是选择题，处理选项
            if (type.equals("multiple-choice")) {
                @SuppressWarnings("unchecked")
                Map<String, String> options = (Map<String, String>) question.get("options");
                if (options != null && !options.isEmpty()) {
                    String formattedContent = exercise.getContent() + "\n";
                    for (Map.Entry<String, String> option : options.entrySet()) {
                        formattedContent += option.getKey() + ". " + option.getValue() + "\n";
                    }
                    exercise.setContent(formattedContent.trim());
                }
            }
            
            // 保存到数据库
            savedExercises.add(exerciseDao.save(exercise));
        }
        
        return savedExercises;
    }
    
    @Override
    public List<Map<String, Object>> getHotExercises(Integer page, Integer pageSize, String stage, String subject, String startDate, String endDate) {
        // 模拟热点考题数据
        List<Map<String, Object>> hotExercises = new ArrayList<>();
        
        // 查询条件过滤
        List<Exercise> exercises = exerciseDao.findBySubjectAndGrade(subject, stage);
        
        // 分页处理
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, exercises.size());
        if (start < exercises.size()) {
            exercises = exercises.subList(start, end);
        } else {
            exercises = Collections.emptyList();
        }
        
        // 构建响应数据
        for (int i = 0; i < exercises.size(); i++) {
            Exercise exercise = exercises.get(i);
            Map<String, Object> item = new HashMap<>();
            item.put("id", exercise.getId());
            item.put("title", "热点考题 " + (i + 1 + start));
            item.put("subject", exercise.getSubject());
            item.put("grade", exercise.getGrade());
            item.put("content", exercise.getContent());
            item.put("frequency", new Random().nextInt(10000) + 1000); // 模拟频次数据
            item.put("date", exercise.getCreatedTime().format(DateTimeFormatter.ISO_LOCAL_DATE));
            
            hotExercises.add(item);
        }
        
        return hotExercises;
    }
    
    @Override
    public int countHotExercises(String stage, String subject, String startDate, String endDate) {
        if (subject == null || subject.isEmpty()) {
            return (int)exerciseDao.count();
        }
        return (int)exerciseDao.countBySubjectAndGrade(subject, stage);
    }
    
    @Override
    public List<Map<String, Object>> getMistakes(Integer page, Integer pageSize, String stage, String subject, String mistakeType) {
        List<Map<String, Object>> mistakes = new ArrayList<>();
        
        // 获取练习题数据
        List<Exercise> exercises = exerciseDao.findBySubjectAndGrade(subject, stage);
        
        // 分页处理
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, exercises.size());
        if (start < exercises.size()) {
            exercises = exercises.subList(start, end);
        } else {
            exercises = Collections.emptyList();
        }
        
        // 随机生成一些错误率和错误原因
        String[] errorReasons = {
            "概念理解错误", 
            "计算过程错误", 
            "公式使用错误", 
            "题目理解错误", 
            "解题步骤错误"
        };
        
        Random random = new Random();
        
        for (int i = 0; i < exercises.size(); i++) {
            Exercise exercise = exercises.get(i);
            Map<String, Object> item = new HashMap<>();
            item.put("id", exercise.getId());
            item.put("title", "高频错题 " + (i + 1 + start));
            item.put("subject", exercise.getSubject());
            item.put("grade", exercise.getGrade());
            item.put("content", exercise.getContent());
            item.put("errorRate", random.nextInt(50) + 30 + "%"); // 30%-80%的错误率
            item.put("errorReason", errorReasons[random.nextInt(errorReasons.length)]);
            
            mistakes.add(item);
        }
        
        return mistakes;
    }
    
    @Override
    public int countMistakes(String stage, String subject, String mistakeType) {
        if (subject == null || subject.isEmpty()) {
            return (int)exerciseDao.count();
        }
        return (int)exerciseDao.countBySubjectAndGrade(subject, stage);
    }
    
    @Override
    public Map<String, Object> getMistakesStats(String stage, String subject) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("conceptual", 35);
        stats.put("calculation", 25);
        stats.put("application", 20);
        stats.put("comprehension", 15);
        stats.put("other", 5);
        return stats;
    }
    
    @Override
    public List<Map<String, String>> getTextbookChapters(String subject, String textbook) {
        List<Map<String, String>> chapters = new ArrayList<>();
        
        // 根据学科返回模拟的教材章节
        for (int i = 1; i <= 10; i++) {
            Map<String, String> chapter = new HashMap<>();
            chapter.put("id", String.valueOf(i));
            chapter.put("title", getChapterTitle(subject, i));
            chapters.add(chapter);
        }
        
        return chapters;
    }
    
    @Override
    public List<Map<String, Object>> getExerciseHistory(String teacherId, int page, int size) {
        List<Map<String, Object>> history = new ArrayList<>();
        
        // 根据教师ID查询练习题
        List<Exercise> exercises = exerciseDao.findByTeacherId(teacherId);
        
        // 分页处理
        int start = (page - 1) * size;
        int end = Math.min(start + size, exercises.size());
        if (start < exercises.size()) {
            exercises = exercises.subList(start, end);
        } else {
            exercises = Collections.emptyList();
        }
        
        // 按不同日期分组
        Map<LocalDate, List<Exercise>> groupedExercises = exercises.stream()
                .collect(Collectors.groupingBy(
                        e -> e.getCreatedTime().toLocalDate()
                ));
        
        // 构建响应数据
        for (Map.Entry<LocalDate, List<Exercise>> entry : groupedExercises.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", entry.getKey().format(DateTimeFormatter.ISO_LOCAL_DATE));
            
            List<Map<String, Object>> items = new ArrayList<>();
            for (Exercise exercise : entry.getValue()) {
                Map<String, Object> exerciseItem = new HashMap<>();
                exerciseItem.put("id", exercise.getId());
                exerciseItem.put("subject", exercise.getSubject());
                exerciseItem.put("grade", exercise.getGrade());
                exerciseItem.put("topic", exercise.getTopic());
                exerciseItem.put("questionType", exercise.getQuestionType());
                exerciseItem.put("content", exercise.getContent());
                exerciseItem.put("answer", exercise.getAnswer());
                exerciseItem.put("analysis", exercise.getAnalysis());
                exerciseItem.put("difficulty", exercise.getDifficulty());
                exerciseItem.put("teacherId", exercise.getTeacherId());
                exerciseItem.put("createdTime", exercise.getCreatedTime());
                items.add(exerciseItem);
            }
            
            item.put("items", items);
            history.add(item);
        }
        
        return history;
    }
    
    private String convertQuestionType(String type) {
        if (type == null) return "multiple-choice";
        
        if (type.contains("选择题")) {
            return "multiple-choice";
        } else if (type.contains("填空题")) {
            return "fill-blank";
        } else if (type.contains("判断题")) {
            return "true-false";
        } else if (type.contains("解答题") || type.contains("计算题")) {
            return "calculation";
        } else if (type.contains("简答题") || type.contains("论述题")) {
            return "short-answer";
        } else {
            return "multiple-choice"; // 默认选择题
        }
    }
    
    private String convertFrontendType(String type) {
        switch (type) {
            case "multiple-choice":
                return "选择题";
            case "fill-blank":
                return "填空题";
            case "true-false":
                return "判断题";
            case "calculation":
                return "解答题";
            case "short-answer":
                return "简答题";
            default:
                return "选择题";
        }
    }
    
    private Map<String, String> parseOptions(String content) {
        Map<String, String> options = new LinkedHashMap<>();
        String[] lines = content.split("\n");
        
        for (int i = 1; i < lines.length; i++) {
            String line = lines[i].trim();
            if (line.isEmpty()) continue;
            
            if (line.length() >= 2 && Character.isLetter(line.charAt(0)) && line.charAt(1) == '.') {
                String key = line.substring(0, 1);
                String value = line.substring(2).trim();
                options.put(key, value);
            }
        }
        
        return options;
    }
    
    private String getExampleQuestion(String subject, String stage, int index) {
        if ("数学".equals(subject)) {
            if (stage.contains("小")) {
                return String.format("计算题%d：求解方程 %dx + %d = %d。", index, index+1, index*2, index*5);
            } else {
                return String.format("计算题%d：已知函数f(x) = %dx² + %dx + %d，求f'(x)。", index, index, index*2-1, index*3);
            }
        } else if ("语文".equals(subject)) {
            return String.format("阅读题%d：阅读下面的文章，回答问题...", index);
        } else if ("英语".equals(subject)) {
            return String.format("选择题%d：Choose the correct answer: The book __ on the desk.", index);
        } else if ("物理".equals(subject)) {
            return String.format("计算题%d：一个物体以初速度v = %d m/s抛出，重力加速度g = 9.8 m/s²，求物体到达最高点的时间。", index, index*5);
        } else if ("化学".equals(subject)) {
            return String.format("实验题%d：描述用%s检验%s的实验过程。", index, "酚酞试液", "NaOH溶液");
        } else {
            return String.format("题目%d：这是一道%s题目的示例。", index, subject);
        }
    }
    
    private String getChapterTitle(String subject, int chapterIndex) {
        Map<String, String[]> subjectChapters = new HashMap<>();
        subjectChapters.put("数学", new String[] {
            "数与代数",
            "方程与不等式",
            "函数",
            "空间与图形",
            "概率与统计",
            "几何证明",
            "三角函数",
            "数列",
            "立体几何",
            "解析几何"
        });
        subjectChapters.put("语文", new String[] {
            "文言文阅读",
            "现代文阅读",
            "古诗词鉴赏",
            "名著阅读",
            "作文",
            "语言文字运用",
            "口语交际",
            "写作技巧",
            "中国文学史",
            "外国文学史"
        });
        subjectChapters.put("英语", new String[] {
            "语法",
            "词汇",
            "阅读理解",
            "写作",
            "听力",
            "口语",
            "完形填空",
            "短文改错",
            "书面表达",
            "翻译"
        });
        subjectChapters.put("物理", new String[] {
            "力学",
            "热学",
            "电磁学",
            "光学",
            "原子物理",
            "机械振动和机械波",
            "分子动理论",
            "电场和磁场",
            "狭义相对论",
            "量子物理初步"
        });
        subjectChapters.put("化学", new String[] {
            "物质结构",
            "化学反应原理",
            "元素及其化合物",
            "有机化学基础",
            "实验化学",
            "化学与生活",
            "化学计算",
            "电化学",
            "物质结构与性质",
            "化学反应速率和化学平衡"
        });
        
        String[] chapters = subjectChapters.getOrDefault(subject, new String[] {
            "第一章", "第二章", "第三章", "第四章", "第五章", "第六章", "第七章", "第八章", "第九章", "第十章"
        });
        
        int index = (chapterIndex - 1) % chapters.length;
        return "第" + chapterIndex + "章 " + chapters[index];
    }
    
    @Override
    public List<Exercise> generateExercises(String stage, String subject, String textbook, String chapter, int count, List<String> questionTypes, String teacherId) {
        List<Exercise> exercises = new ArrayList<>();
        
        for (String questionType : questionTypes) {
            // 为每种题型生成一定数量的题目
            int typeCount = count / questionTypes.size();
            if (typeCount == 0) typeCount = 1;
            
            ExerciseRequest request = new ExerciseRequest();
            request.setSubject(subject);
            request.setGrade(stage);
            request.setTopic(chapter);
            request.setQuestionType(convertFrontendType(questionType));
            request.setDifficulty("中等");
            request.setCount(typeCount);
            request.setTeacherId(teacherId);
            
            List<Exercise> generatedExercises = generateExercises(request);
            exercises.addAll(generatedExercises);
        }
        
        return exercises;
    }
    
    @Override
    public List<Exercise> generateExercises(String stage, String subject, String textbook, String chapter, int count, List<String> questionTypes) {
        return generateExercises(stage, subject, textbook, chapter, count, questionTypes, com.education.ai.util.TeacherContext.getCurrentTeacherId());
    }

    @Override
    public Exercise findById(Long id) {
        return exerciseDao.findById(id).orElse(null);
    }
    
    @Override
    public List<Exercise> findBySubject(String subject) {
        return exerciseDao.findBySubject(subject);
    }
    
    @Override
    public List<Exercise> findBySubjectAndTopic(String subject, String topic) {
        // 由于ExerciseDao中没有直接的findBySubjectAndTopic方法,需要我们自己实现
        return exerciseDao.findAll().stream()
                .filter(e -> e.getSubject().equals(subject) && e.getTopic().equals(topic))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<Exercise> findBySubjectAndType(String subject, String type) {
        // 由于ExerciseDao中没有直接的findBySubjectAndType方法,需要我们自己实现
        return exerciseDao.findAll().stream()
                .filter(e -> e.getSubject().equals(subject) && e.getQuestionType().equals(type))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<Exercise> findByDifficultyLevel(Integer level) {
        // 将整数难度转换为字符串难度描述
        String difficultyDesc;
        switch (level) {
            case 1:
                difficultyDesc = "简单";
                break;
            case 2:
                difficultyDesc = "中等";
                break;
            case 3:
                difficultyDesc = "困难";
                break;
            default:
                difficultyDesc = "中等";
        }
        
        // 使用ExerciseDao中的findByDifficulty方法
        return exerciseDao.findByDifficulty(difficultyDesc);
    }
    
    @Override
    public Exercise save(Exercise exercise) {
        return exerciseDao.save(exercise);
    }
    
    @Override
    public List<Exercise> saveAll(List<Exercise> exercises) {
        return exerciseDao.saveAll(exercises);
    }
    
    @Override
    public void deleteById(Long id) {
        exerciseDao.deleteById(id);
    }
    
    @Override
    public List<Exercise> getRecommendedExercises(String studentId, Integer count) {
        log.info("为学生[{}]推荐{}道习题", studentId, count);
        
        try {
            // 1. 获取学生错题集中的题目类型和知识点
            String mistakeSql = "SELECT e.topic, e.question_type, e.difficulty " +
                "FROM student_mistake_collection m " +
                "JOIN exercises e ON m.exercise_id = e.id " +
                "WHERE m.student_id = ? AND m.mistake_count > 0 " +
                "ORDER BY m.last_mistake_time DESC LIMIT 10";
            
            List<Map<String, Object>> mistakeData = jdbcTemplate.queryForList(mistakeSql, studentId);
            
            // 2. 获取学生最近的练习记录
            String practiceSql = "SELECT subject, topic FROM student_practice_sessions " +
                "WHERE student_id = ? ORDER BY end_time DESC LIMIT 5";
            
            List<Map<String, Object>> practiceData = jdbcTemplate.queryForList(practiceSql, studentId);
            
            // 3. 如果有错题记录，优先推荐相关知识点的习题
            if (!mistakeData.isEmpty()) {
                List<String> topics = new ArrayList<>();
                List<String> types = new ArrayList<>();
                List<String> difficulties = new ArrayList<>();
                
                for (Map<String, Object> mistake : mistakeData) {
                    if (mistake.get("topic") != null) {
                        topics.add(mistake.get("topic").toString());
                    }
                    if (mistake.get("question_type") != null) {
                        types.add(mistake.get("question_type").toString());
                    }
                    if (mistake.get("difficulty") != null) {
                        difficulties.add(mistake.get("difficulty").toString());
                    }
                }
                
                // 从错题的知识点中随机选择一个
                if (!topics.isEmpty()) {
                    String randomTopic = topics.get(new Random().nextInt(topics.size()));
                    List<Exercise> similarExercises = exerciseDao.findByTopic(randomTopic);
                    
                    // 如果找到足够的相似习题，返回它们
                    if (similarExercises.size() >= count) {
                        Collections.shuffle(similarExercises);
                        return similarExercises.subList(0, Math.min(count, similarExercises.size()));
                    }
                }
            }
            
            // 4. 如果有练习记录，根据最近练习的学科和主题推荐习题
            if (!practiceData.isEmpty()) {
                Map<String, Object> recentPractice = practiceData.get(0);
                String subject = recentPractice.get("subject") != null ? 
                    recentPractice.get("subject").toString() : null;
                String topic = recentPractice.get("topic") != null ? 
                    recentPractice.get("topic").toString() : null;
                
                if (subject != null) {
                    List<Exercise> subjectExercises;
                    if (topic != null) {
                        subjectExercises = exerciseDao.findBySubjectAndGradeAndTopic(subject, null, topic);
                    } else {
                        subjectExercises = exerciseDao.findBySubject(subject);
                    }
                    
                    // 如果找到足够的相关习题，返回它们
                    if (subjectExercises.size() >= count) {
                        Collections.shuffle(subjectExercises);
                        return subjectExercises.subList(0, Math.min(count, subjectExercises.size()));
                    }
                }
            }
            
            // 5. 如果以上策略都没有找到足够的题目，返回随机题目
            List<Exercise> allExercises = exerciseDao.findAll();
            
            // 如果题库中的题目数量小于请求数量，返回全部题目
            if (allExercises.size() <= count) {
                return allExercises;
            }
            
            // 随机选择count个题目
            Collections.shuffle(allExercises);
            return allExercises.subList(0, count);
        } catch (Exception e) {
            log.error("获取推荐习题失败: {}", e.getMessage(), e);
            // 出现异常时返回随机题目
            List<Exercise> allExercises = exerciseDao.findAll();
            Collections.shuffle(allExercises);
            return allExercises.subList(0, Math.min(count, allExercises.size()));
        }
    }
} 